<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />
		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">
					<uni-forms-item label="采购计划单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入采购计划单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item label="采购员" name="purchase_user_id">
						<uni-data-select mode="underline" placeholder="请选择采购员" v-model="form.purchase_user_id"
							:localdata="account_list" :clear="false" @change="selectChange"/>
					</uni-forms-item>
					<uni-forms-item label="交货日期" name="delivery_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="请选择交货日期" :clear-icon="false"
								v-model="form.delivery_date" @show="car_popup_Show = false" @maskClick="car_popup_Show = true"
								@change="car_popup_Show = true" :border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注：" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
			</view>
			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" :animation="cartShakeAnim" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${form.bom_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(form.bom_list.length) }" v-show="car_popupShow"
					@click.stop="save">提 交</view>
				<view style="margin-left: auto;" v-show="!car_popupShow"><u--text text="点击查看" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" :title="'已选产品'" @close="car_popupShow = false"
				height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.bom_list" @query="queryList_car">
					<template #top>
						<view class="zpagin_top">
							<view class="btn-box">
								<view>
									<u-button type="primary" size="small" text="选择产品" @click="popupShow = true"></u-button>
								</view>
							</view>
						</view>
					</template>

					<uni-card v-for="(item, index) in form.bom_list" :key="index" margin="5px" spacing="0">
						<template v-slot:title>
							<uni-list>
								<uni-list-item :title="item.name" :note="item.code" thumbSize="lg">
									<template v-slot:footer>
										<up-icon name="trash" color="red" size="28" @click="removeTransfer(index)" />
									</template>
								</uni-list-item>
							</uni-list>
						</template>
						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con" style="align-items: normal;">
							<view class="ctent" style="flex: none;">库存：</view>
							<view class="ctent">{{ item.inventory_info }}</view>
						</view>
						<view class="ctent">损耗率：{{ item.loss }}%</view>
						<uni-forms-item label="供应商：" :name="`bom_list[${index}].p_supplier_id`" required
							:rules="[{ required: true, type: 'number', errorMessage: `请选择【${item.name}】的供应商` }]">
							<uni-data-select mode="underline" placeholder="请选择供应商" v-model="item.p_supplier_id"
								:localdata="get_supplier_list(item)" :clear="false"
								@change="handleNumInput({ value: item.p_num }, item)" />
						</uni-forms-item>
						<uni-forms-item label="采购单位：" :name="`bom_list[${index}].p_unit`" required
							:rules="[{ required: true, errorMessage: `请选择【${item.name}】的采购单位` }]">
							<uni-data-select mode="underline" placeholder="采购单位" v-model="item.p_unit" :localdata="getUnitList(item)"
								:clear="false" @change="handleUnitChange(item)" />
						</uni-forms-item>
						<view class="con">
							<view class="ctent date_text" style="flex: none;">采购数量：</view>
							<custom-num-box v-model="item.p_num" :min="0" @change="handleNumInput($event, item)"
								:asyncChange="true"></custom-num-box>
						</view>
						<view class="ctent">总价：{{ item.gross_price ||'' }}</view>
						<view class="con">
							<view class="ctent date_text" style="flex: none;">优惠率(%)：</view>
							<custom-num-box v-model="item.discount" :min="0" @change="handleDiscountInput($event, item)"
								:asyncChange="true"></custom-num-box>
						</view>
						<view class="con">
							<view class="ctent date_text" style="flex: none;">最终价：</view>
							<custom-num-box v-model="item.total_price" :min="0" @change="handleTotalInput($event, item)"
								:asyncChange="true"></custom-num-box>
						</view>
					</uni-card>
					<view slot="bottom">
						<view class="zhanwei"></view>
					</view>
				</z-paging>
				<custom-popup :popupShow="popupShow" mode="center" :title="'选择产品'" width="96%" height="60%"
					:closeOnClickOverlay="false" :safeAreaInsetBottom="false"  @close="popupShow = false">
					<FlyBall ref="flyBall" />
					<z-paging v-if="popupShow" ref="paging" :fixed="false" v-model="dataList" @query="queryList">
						<template #top>
							<view class="zpagin_top">
								<view class="search">
									<custom-search v-model="searchVal" @search="refreshList" placeholder="请输入产品名称或编号" />
								</view>
							</view>
						</template>
						<uni-card v-for="(item, index) in dataList" :key="item.id" margin="5px" spacing="0">
							<template v-slot:title>
								<uni-list>
									<uni-list-item :title="item.name" :note="item.code" thumbSize="lg">
										<template v-slot:footer>
											<view :id="`goods-btn${index}`">
												<u-button type="primary" size="small" shape="circle" text="添加" @click="hanldAddWar(index, item)"
													:disabled="isInTransfer(item.id)"></u-button>
											</view>
										</template>
									</uni-list-item>
								</uni-list>
							</template>
							<view class="ctent">规格：{{ item.specification }}</view>
							<view class="con">
								<view class="ctent">损耗率：{{ item.loss }}%</view>
							</view>
						</uni-card>
					</z-paging>
				</custom-popup>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import puPlanApi from '../../../api/purchase/pu_plan'
import { generateCode, debounce, shakeCartIcon, getRectDom } from '@/utils/index.js';
import { getSupplierPrice } from '../../../utils/purchase'
import Decimal from 'decimal.js-light';
import FlyBall from '@/components/flyBall'

//页面标题
const pageInfo = reactive({
	navbarTitle: '采购计划',
	type: '',
	edit_id: null,
});
onLoad(option => {
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(修改)'
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(新增)'
		form.code = generateCode('PL')
	}
	get_account_list()
})



//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('PL')
	}
}

const refForm = ref(null)
const form = reactive({
	code: '',
	purchase_user_id: null,
	delivery_date: '',
	desc: '',
	bom_list: []
})
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入采购计划单号' }] },
	delivery_date: { rules: [{ required: true, errorMessage: '请选择交货日期' }] },
}

function get_detail(id) {
	puPlanApi.purchase_plan_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		form.bom_list = res.purchase_plan_boms.map(v => {
			const total = parseFloat(v.supplier_price) * v.num
			return {
				id: v.bom.id,
				code: v.bom.code,
				name: v.bom.name,
				specification: v.bom.specification,
				supplier_info: v.bom.supplier_info,
				supplier: v.bom.supplier,
				stock_info: v.bom.stock_info,
				loss: v.bom.loss,
				p_supplier_id: v.supplier_id,
				p_unit: v.unit,
				p_num: v.num,
				discount: parseFloat(v.discount),
				total_price: v.total_price,
				gross_price: parseFloat(total.toFixed(2)),
				unit_main: v.bom.unit_main,
				unit_assist_one_ratio: v.bom.unit_assist_one_ratio,
				unit_assist_two_ratio: v.bom.unit_assist_two_ratio,
				unit_assist_one: v.bom.unit_assist_one,
				unit_assist_two: v.bom.unit_assist_two,
				unit_main_price: v.bom.unit_main_price,
				unit_assist_one_price: v.bom.unit_assist_one_price,
				unit_assist_two_price: v.bom.unit_assist_two_price,
				inventory_info: v.bom.stock_info.map(v => (`${v.warehouse_name}【${v.unit_info}】`)).join('、'),
			}
		})

	})
}

function selectChange(v){
	const obj = account_list.value.find(k=>k.value===v)
	form.purchase_full_name = obj?.text
}

const paging = ref(null)
const searchVal = ref('')
const dataList = ref([])
function queryList(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		if_open: 1,
		style: 1,
		search: searchVal.value
	}
	puPlanApi.get_bom(params).then((res) => {
		paging.value.complete(res.results);
	})
}
function refreshList() {
	paging.value.reload();
}

function get_supplier_list(item) {
	const supplier = item.supplier
	const supplier_info = JSON.parse(item.supplier_info || '[]')
	const infoMap = {}
	supplier_info.forEach(v => {
		infoMap[v.supplier_id] = v
	})

	// 组装显示
	return supplier.map(s => {
		const info = infoMap[s.id] || {}
		const price = info.price || '-'
		return {
			value: s.id,
			text: s.name + '【采购价：' + price + '元/' + item.unit_main + '】'
		}
	})
}

function getUnitList(item) {
	const units = [item.unit_main, item.unit_assist_one, item.unit_assist_two]
	// 过滤掉为 null 或 undefined 的单位
	return units.filter(Boolean).map(v => ({
		text: v, value: v
	}))
}

function getUnitNum(row) {
	if (row.p_unit == row.unit_main) {
		return row.p_num
	}
	if (row.p_unit == row.unit_assist_one) {
		return row.p_num * row.unit_assist_one_ratio
	}
	if (row.p_unit == row.unit_assist_two) {
		return row.p_num * row.unit_assist_one_ratio * row.unit_assist_two_ratio
	}
	return 0
}

function handleUnitChange(row) {
	if (row.market_unit == row.unit_main) {
		row.cost = row.all_cost * 1
		row.main_price = row.unit_main_price
	}
	if (row.market_unit == row.unit_assist_one) {
		row.cost = row.all_cost * row.unit_assist_one_ratio
		row.main_price = row.unit_assist_one_price
	}
	if (row.market_unit == row.unit_assist_two) {
		row.cost = row.all_cost * row.unit_assist_one_ratio * row.unit_assist_two_ratio
		row.main_price = row.unit_assist_two_price
	}
	handleNumInput({ value: row.p_num }, row)
}

function handleNumInput({ value }, row) {
	row.p_num = value
	const supplier_price = getSupplierPrice(row)
	const all = new Decimal(supplier_price).mul(new Decimal(getUnitNum(row) || 0))
	const discount = new Decimal(row.discount || 0)
	const total_price = all.sub(all.mul(discount).div(100))
	row.total_price = total_price.toDecimalPlaces(2).toNumber()
	row.gross_price = all.toDecimalPlaces(2).toNumber()
}
function handleDiscountInput(e, row) {
	row.discount = e.value
	const supplier_price = getSupplierPrice(row)
	const all = new Decimal(supplier_price).mul(new Decimal(getUnitNum(row) || 0))
	const discount = new Decimal(row.discount || 0)
	// total = all - all * discount / 100
	const total_price = all.sub(all.mul(discount).div(100))
	row.total_price = total_price.toDecimalPlaces(2).toNumber()
}
function handleTotalInput(e, row) {
	row.total_price = e.value
	// .mul(x)	*	乘法 multiply
	// .sub(x)	-	减法 subtract
	// .add(x)	+	加法 add
	// .div(x)	/	除法 divide
	const supplier_price = getSupplierPrice(row)
	const all = new Decimal(supplier_price).mul(new Decimal(getUnitNum(row) || 0))
	if (all.isZero()) {
		row.discount = 0
		return
	}
	const discount = new Decimal(100).mul(all.sub(new Decimal(row.total_price || 0))).div(all)
	// 保留最多 8 位小数
	row.discount = discount.toDecimalPlaces(8).toNumber()
}

//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			puPlanApi.post_purchase_plan(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			puPlanApi.patch_purchase_plan(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		console.log(error)
		uni.$u.toast(error[0].errorMessage);
	})
}

const account_list = ref([])
function get_account_list() {
	const params = { page: 1, page_size: 99999 };
	puPlanApi.get_staff(params).then(res => {
		account_list.value = res.results.map(v => ({
			text: v.full_name,
			value: v.id
		}))
	})
}

const paging_car = ref(null)
const car_popup_Show = ref(true)
const popupShow = ref(false)
const car_popupShow = ref(false)
function queryList_car() {
	paging_car.value.complete(form.bom_list);
}
function isInTransfer(id) {
	return form.bom_list.some(item => item.id === id)
}

function removeTransfer(index) {
	form.bom_list.splice(index, 1)
	paging_car.value.complete(form.bom_list);
}


const cartShakeAnim = ref()
const flyBall = ref({});
const { proxy } = getCurrentInstance()
async function hanldAddWar(index, item) {
	const dataIndex = `#goods-btn${index}`
	const startRect = await getRectDom(dataIndex, proxy);
	const endRect = await getRectDom('.cartIcon', proxy);
	//小球动画完成回调函数
	flyBall.value.launch(startRect, endRect, () => {
		if (isInTransfer(item.id)) return;
		form.bom_list.push({
			...item,
			market_unit: item.unit_main || '', // 默认设置为 unit_main
			main_price: item.unit_main_price,
			cost: item.all_cost,
			discount: item.discount || 0,
			inventory_info: item.stock_info.map(v => (`${v.warehouse_name}【${v.unit_info}】`)).join('、'),
			p_num: 0
		})
		cartShakeAnim.value = shakeCartIcon()
	})
}


//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('pu_plan:refresh')
		}
	})
}
</script>
<style lang="scss" scoped></style>